package top.hongsheng9527.bookdownload.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.hongsheng9527.bookdownload.service.CrawlService;
import top.hongsheng9527.bookdownload.vo.CrawlSingleTask;
import top.hongsheng9527.bookdownload.vo.CrawlSource;
import top.hongsheng9527.bookdownload.vo.PageBean;
import top.hongsheng9527.bookdownload.vo.ResultBean;

/**
 * @author Wanghs
 * @create 2022/4/8
 * @description
 */
@RestController
@RequestMapping("/crawl")
@Api("爬虫类")
@RequiredArgsConstructor
public class CrawlController {

    private final CrawlService crawlService;


    /**
     * 新增爬虫源
     */
    @ApiOperation(value = "新增爬虫源")
    @PostMapping("/addCrawlSource")
    public ResultBean<Void> addCrawlSource(@ApiParam("爬虫源名称") @RequestParam("sourceName") String sourceName,
                                           @ApiParam("爬虫源规则：JSON格式") @RequestParam("crawlRule") String crawlRule,
                                           @ApiParam("爬虫源网址") @RequestParam("address") String address) {
        CrawlSource source = new CrawlSource();
        source.setAddress(address);
        source.setSourceName(sourceName);
        source.setCrawlRule(crawlRule);
        source.setSourceStatus((byte) 0);
        crawlService.addCrawlSource(source);
        return ResultBean.ok();

    }

    /**
     * 爬虫源模糊查询
     */
    @ApiOperation(value = "根据网站网址查询爬虫源")
    @GetMapping("/getCrawlByAddress")
    public ResultBean<CrawlSource> listCrawlByPage(@ApiParam("爬虫源网址") @RequestParam(value = "address") String address) {

        return ResultBean.ok(crawlService.listCrawlByPage(address));
    }

    /**
     * 新增单本采集任务
     */
    @ApiOperation(value = "新增txt下载任务")
    @PostMapping("/addCrawlSingleTask")
    public ResultBean<Void> addCrawlSingleTask(@ApiParam("小说名称") @RequestParam String bookName,
                                               @ApiParam("作者名称") @RequestParam String authorName,
                                               @ApiParam("小说编号，通常在url里") @RequestParam String sourceBookId,
                                               @ApiParam("爬虫源名称") @RequestParam String sourceName,
                                               @ApiParam("爬虫源id") @RequestParam Integer sourceId) {
        CrawlSingleTask singleTask = new CrawlSingleTask();
        singleTask.setAuthorName(authorName);
        singleTask.setBookName(bookName);
        singleTask.setSourceBookId(sourceBookId);
        singleTask.setSourceName(sourceName);
        singleTask.setSourceId(sourceId);
        singleTask.setCatId(1);
        crawlService.addCrawlSingleTask(singleTask);

        return ResultBean.ok();

    }

}
